﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace TimedTask.Core
{
    public class DownFileTask : BaskTask<String>
    {
        public static string SavePath = "";//保存路径 
        public static int YesNum = 0;//成功个数
        public static int NoNum = 0;//失败个数

        public static double DownloadedBytes = 0;//已下载量 - 用于计算下载速度 
        /// <summary>
        /// 多线程同步的字段
        /// </summary>
        private static object _lock = new object();

        private DownFileTask() : base(null) { }
        public DownFileTask(IEnumerable<string> collection) : base(collection)
        {
            YesNum = 0;
            NoNum = 0;

            //ATimer.setInterval(1000, () =>
            //{
            //    Console.WriteLine("当前下载速度为：" + (DownloadedBytes * 1000.0) / 1000 / 1000);
            //    DownloadedBytes = 0;
            //});
        }

        /// <summary>
        /// 每次多线程都到这里来,处理多线程
        /// </summary>
        /// <param name="pendingValue"列表ID></param>
        /// <returns></returns>
        protected override DoWorkResult DoWork(string url)
        {
            try
            {
                if (url.Contains("."))
                {
                    double downloadBytes = 0;//已经下载
                    int totalBytes = 0;
                    int bufferSize = 1024 * 100;//每次读取的字节数
                    string suffix = url.Substring(url.LastIndexOf("."));
                    string fileName = SavePath + DateTime.Now.ToString("yyyyMMddHHmmssffff") + new Random().Next(10, 1000) + suffix;
                    string dirPath = fileName.Substring(0, fileName.LastIndexOf(@"\") + 1);
                    MSL.Tool.IOHelper.CreateFolder(dirPath);

                    try
                    {
                        HttpWebRequest request = (HttpWebRequest)FileWebRequest.Create(url);
                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                        byte[] buffer = new byte[bufferSize];
                        totalBytes = (int)response.ContentLength;

                        using (Stream stream = response.GetResponseStream())
                        {
                            using (FileStream writer = File.Create(fileName, bufferSize))
                            {
                                int bytesRead;
                                do
                                {
                                    bytesRead = stream.Read(buffer, 0, buffer.Length);
                                    downloadBytes += bytesRead;
                                    writer.Write(buffer, 0, bytesRead);

                                    //lock (_lock)
                                    //{
                                    DownloadedBytes += bytesRead;
                                    //}
                                } while (bytesRead > 0);
                            }
                        }
                        if (File.Exists(fileName))
                            YesNum++;
                        else
                            NoNum++;

                    }
                    catch (Exception ex)
                    {
                        NoNum++;
                        MSL.Tool.LogHelper.SaveErrorLog("下载文件异常", ex);
                    }
                }
                return DoWorkResult.ContinueThread;//没有异常让线程继续跑..
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return DoWorkResult.AbortCurrentThread;//有异常,可以终止当前线程.当然.也可以继续,
            }
        }
    }
}
